import React, { useState } from 'react'
import { 
  Card, 
  Form, 
  Input, 
  Select, 
  Upload, 
  Button, 
  Space, 
  Typography, 
  Divider, 
  Tag,
  InputNumber,
  Tabs,
  Row,
  Col,
  List,
  Avatar,
  Popconfirm
} from 'antd'
import { 
  InfoCircleOutlined,
  EnvironmentOutlined,
  ClockCircleOutlined,
  UserOutlined,
  AppstoreOutlined,
  SoundOutlined,
  PlusOutlined,
  DeleteOutlined,
  UploadOutlined,
  FileImageOutlined
} from '@ant-design/icons'
import { 
  LocationType, 
  LightingCondition, 
  type StoryboardScene,
  type SceneCharacter,
  type SceneProp
} from '../../../types/document'

const { Title, Text } = Typography
const { TextArea } = Input
const { TabPane } = Tabs

export interface SceneDetailPanelProps {
  scene: StoryboardScene
  onChange?: (updates: Partial<StoryboardScene>) => void
  disabled?: boolean
}

/**
 * 场景详情面板组件
 * 提供场景的完整编辑功能，包括基础信息、角色道具、制作信息等
 */
export const SceneDetailPanel: React.FC<SceneDetailPanelProps> = ({
  scene,
  onChange,
  disabled = false
}) => {
  const [form] = Form.useForm()
  const [activeTab, setActiveTab] = useState('basic')

  // 地点类型选项
  const locationTypeOptions = [
    { label: '室内', value: LocationType.INTERIOR },
    { label: '室外', value: LocationType.EXTERIOR },
    { label: '车内', value: LocationType.VEHICLE },
    { label: '水下', value: LocationType.UNDERWATER },
    { label: '航拍', value: LocationType.AERIAL }
  ]

  // 光照条件选项
  const lightingOptions = [
    { label: '白天自然光', value: LightingCondition.NATURAL_DAY },
    { label: '夜晚', value: LightingCondition.NATURAL_NIGHT },
    { label: '黎明', value: LightingCondition.NATURAL_DAWN },
    { label: '黄昏', value: LightingCondition.NATURAL_DUSK },
    { label: '强人工光', value: LightingCondition.ARTIFICIAL_BRIGHT },
    { label: '昏暗光线', value: LightingCondition.ARTIFICIAL_DIM },
    { label: '混合光线', value: LightingCondition.MIXED }
  ]

  // 优先级选项
  const priorityOptions = [
    { label: '低', value: 'low', color: 'default' },
    { label: '普通', value: 'normal', color: 'blue' },
    { label: '高', value: 'high', color: 'orange' },
    { label: '紧急', value: 'urgent', color: 'red' }
  ]

  // 复杂度选项
  const complexityOptions = [
    { label: '简单', value: 'simple', color: 'green' },
    { label: '中等', value: 'medium', color: 'orange' },
    { label: '复杂', value: 'complex', color: 'red' }
  ]

  // 处理字段更新
  const handleFieldChange = (field: string, value: any) => {
    const updates: Partial<StoryboardScene> = {}
    
    if (field.startsWith('sceneLocation.')) {
      const locationField = field.replace('sceneLocation.', '')
      updates.sceneLocation = { ...scene.sceneLocation, [locationField]: value }
    } else if (field.startsWith('production.')) {
      const productionField = field.replace('production.', '')
      updates.production = { ...scene.production, [productionField]: value }
    } else if (field.startsWith('audioElements.')) {
      const audioField = field.replace('audioElements.', '')
      updates.audioElements = { ...scene.audioElements, [audioField]: value }
    } else {
      updates[field as keyof StoryboardScene] = value
    }
    
    onChange?.(updates)
  }

  // 添加角色
  const handleAddCharacter = () => {
    const newCharacter: SceneCharacter = {
      id: `char_${Date.now()}`,
      name: '新角色',
      role: 'main'
    }
    
    const characters = scene.elements?.characters || []
    handleFieldChange('elements.characters', [...characters, newCharacter])
  }

  // 删除角色
  const handleRemoveCharacter = (index: number) => {
    const characters = scene.elements?.characters || []
    const updated = characters.filter((_, i) => i !== index)
    handleFieldChange('elements.characters', updated)
  }

  // 添加道具
  const handleAddProp = () => {
    const newProp: SceneProp = {
      id: `prop_${Date.now()}`,
      name: '新道具',
      importance: 'featured'
    }
    
    const props = scene.elements?.props || []
    handleFieldChange('elements.props', [...props, newProp])
  }

  // 删除道具
  const handleRemoveProp = (index: number) => {
    const props = scene.elements?.props || []
    const updated = props.filter((_, i) => i !== index)
    handleFieldChange('elements.props', updated)
  }

  // 基础信息面板
  const BasicInfoPanel = () => (
    <Form form={form} layout="vertical" disabled={disabled}>
      <Title level={5}>
        <InfoCircleOutlined /> 基础信息
      </Title>
      
      <Form.Item
        label="场景标题"
        name="title"
        rules={[{ required: true, message: '请输入场景标题' }]}
      >
        <Input
          placeholder="为此场景起一个描述性的标题"
          onChange={(e) => handleFieldChange('title', e.target.value)}
          defaultValue={scene.title}
        />
      </Form.Item>

      <Form.Item
        label="场景描述"
        name="description"
      >
        <TextArea
          rows={3}
          placeholder="描述这个场景的整体情况..."
          onChange={(e) => handleFieldChange('description', e.target.value)}
          defaultValue={scene.description}
          showCount
          maxLength={500}
        />
      </Form.Item>

      <Divider />

      <Title level={5}>
        <EnvironmentOutlined /> 拍摄地点
      </Title>

      <Row gutter={16}>
        <Col span={12}>
          <Form.Item
            label="地点名称"
            name="location.name"
          >
            <Input
              placeholder="如：办公室、咖啡厅等"
              onChange={(e) => handleFieldChange('sceneLocation.name', e.target.value)}
              defaultValue={scene.sceneLocation?.name || scene.location}
            />
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item
            label="地点类型"
            name="location.type"
          >
            <Select
              placeholder="选择地点类型"
              onChange={(value) => handleFieldChange('sceneLocation.type', value)}
              defaultValue={scene.sceneLocation?.type}
            >
              {locationTypeOptions.map(option => (
                <Select.Option key={option.value} value={option.value}>
                  {option.label}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>
        </Col>
      </Row>

      <Row gutter={16}>
        <Col span={12}>
          <Form.Item
            label="光照条件"
            name="location.lighting"
          >
            <Select
              placeholder="选择光照条件"
              onChange={(value) => handleFieldChange('sceneLocation.lighting', value)}
              defaultValue={scene.sceneLocation?.lighting}
            >
              {lightingOptions.map(option => (
                <Select.Option key={option.value} value={option.value}>
                  {option.label}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item
            label="地点描述"
            name="location.description"
          >
            <Input
              placeholder="详细地址或环境描述"
              onChange={(e) => handleFieldChange('sceneLocation.description', e.target.value)}
              defaultValue={scene.sceneLocation?.description}
            />
          </Form.Item>
        </Col>
      </Row>
    </Form>
  )

  // 角色和道具面板
  const ElementsPanel = () => (
    <Space direction="vertical" style={{ width: '100%' }} size="large">
      {/* 角色管理 */}
      <Card 
        title={
          <Space>
            <UserOutlined />
            <span>场景角色</span>
          </Space>
        }
        extra={
          <Button
            type="dashed"
            icon={<PlusOutlined />}
            onClick={handleAddCharacter}
            size="small"
          >
            添加角色
          </Button>
        }
        size="small"
      >
        <List
          dataSource={scene.elements?.characters || []}
          renderItem={(character, index) => (
            <List.Item
              actions={[
                <Popconfirm
                  title="确定删除此角色？"
                  onConfirm={() => handleRemoveCharacter(index)}
                  okText="确定"
                  cancelText="取消"
                >
                  <Button
                    type="text"
                    danger
                    icon={<DeleteOutlined />}
                    size="small"
                  />
                </Popconfirm>
              ]}
            >
              <List.Item.Meta
                avatar={<Avatar icon={<UserOutlined />} />}
                title={
                  <Input
                    size="small"
                    defaultValue={character.name}
                    onChange={(e) => {
                      const characters = scene.elements?.characters || []
                      characters[index].name = e.target.value
                      handleFieldChange('elements.characters', [...characters])
                    }}
                  />
                }
                description={
                  <Space>
                    <Select
                      size="small"
                      defaultValue={character.role}
                      style={{ width: 80 }}
                      onChange={(value) => {
                        const characters = scene.elements?.characters || []
                        characters[index].role = value
                        handleFieldChange('elements.characters', [...characters])
                      }}
                    >
                      <Select.Option value="main">主角</Select.Option>
                      <Select.Option value="supporting">配角</Select.Option>
                      <Select.Option value="background">背景</Select.Option>
                    </Select>
                    <Input
                      size="small"
                      placeholder="动作描述"
                      defaultValue={character.action}
                      style={{ width: 120 }}
                      onChange={(e) => {
                        const characters = scene.elements?.characters || []
                        characters[index].action = e.target.value
                        handleFieldChange('elements.characters', [...characters])
                      }}
                    />
                  </Space>
                }
              />
            </List.Item>
          )}
        />
      </Card>

      {/* 道具管理 */}
      <Card 
        title={
          <Space>
            <AppstoreOutlined />
            <span>场景道具</span>
          </Space>
        }
        extra={
          <Button
            type="dashed"
            icon={<PlusOutlined />}
            onClick={handleAddProp}
            size="small"
          >
            添加道具
          </Button>
        }
        size="small"
      >
        <List
          dataSource={scene.elements?.props || []}
          renderItem={(prop, index) => (
            <List.Item
              actions={[
                <Popconfirm
                  title="确定删除此道具？"
                  onConfirm={() => handleRemoveProp(index)}
                  okText="确定"
                  cancelText="取消"
                >
                  <Button
                    type="text"
                    danger
                    icon={<DeleteOutlined />}
                    size="small"
                  />
                </Popconfirm>
              ]}
            >
              <List.Item.Meta
                avatar={<Avatar icon={<AppstoreOutlined />} />}
                title={
                  <Input
                    size="small"
                    defaultValue={prop.name}
                    onChange={(e) => {
                      const props = scene.elements?.props || []
                      props[index].name = e.target.value
                      handleFieldChange('elements.props', [...props])
                    }}
                  />
                }
                description={
                  <Space>
                    <Select
                      size="small"
                      defaultValue={prop.importance}
                      style={{ width: 80 }}
                      onChange={(value) => {
                        const props = scene.elements?.props || []
                        props[index].importance = value
                        handleFieldChange('elements.props', [...props])
                      }}
                    >
                      <Select.Option value="hero">重要</Select.Option>
                      <Select.Option value="featured">一般</Select.Option>
                      <Select.Option value="background">背景</Select.Option>
                    </Select>
                    <Input
                      size="small"
                      placeholder="备注"
                      defaultValue={prop.notes}
                      style={{ width: 120 }}
                      onChange={(e) => {
                        const props = scene.elements?.props || []
                        props[index].notes = e.target.value
                        handleFieldChange('elements.props', [...props])
                      }}
                    />
                  </Space>
                }
              />
            </List.Item>
          )}
        />
      </Card>
    </Space>
  )

  // 制作信息面板
  const ProductionPanel = () => (
    <Form form={form} layout="vertical" disabled={disabled}>
      <Title level={5}>
        <ClockCircleOutlined /> 制作信息
      </Title>

      <Row gutter={16}>
        <Col span={12}>
          <Form.Item
            label="拍摄优先级"
            name="production.priority"
          >
            <Select
              placeholder="选择优先级"
              onChange={(value) => handleFieldChange('production.priority', value)}
              defaultValue={scene.production?.priority || 'normal'}
            >
              {priorityOptions.map(option => (
                <Select.Option key={option.value} value={option.value}>
                  <Tag color={option.color}>{option.label}</Tag>
                </Select.Option>
              ))}
            </Select>
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item
            label="制作复杂度"
            name="production.complexity"
          >
            <Select
              placeholder="选择复杂度"
              onChange={(value) => handleFieldChange('production.complexity', value)}
              defaultValue={scene.production?.complexity || 'simple'}
            >
              {complexityOptions.map(option => (
                <Select.Option key={option.value} value={option.value}>
                  <Tag color={option.color}>{option.label}</Tag>
                </Select.Option>
              ))}
            </Select>
          </Form.Item>
        </Col>
      </Row>

      <Row gutter={16}>
        <Col span={12}>
          <Form.Item
            label="预估拍摄时间"
            name="production.estimatedTime"
          >
            <InputNumber
              min={0}
              precision={1}
              style={{ width: '100%' }}
              placeholder="小时"
              onChange={(value) => handleFieldChange('production.estimatedTime', value)}
              defaultValue={scene.production?.estimatedTime}
              addonAfter="小时"
            />
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item
            label="所需设备"
            name="production.equipment"
          >
            <Input
              placeholder="如：稳定器、灯光等"
              onChange={(e) => handleFieldChange('production.equipment', e.target.value)}
              defaultValue={scene.production?.equipment}
            />
          </Form.Item>
        </Col>
      </Row>

      <Form.Item
        label="制作备注"
        name="production.notes"
      >
        <TextArea
          rows={3}
          placeholder="特殊拍摄要求、注意事项等..."
          onChange={(e) => handleFieldChange('production.notes', e.target.value)}
          defaultValue={scene.production?.notes}
          showCount
          maxLength={500}
        />
      </Form.Item>

      <Divider />

      <Title level={5}>
        <SoundOutlined /> 音频设置
      </Title>

      <Form.Item
        label="对白内容"
        name="audio.dialogue"
      >
        <TextArea
          rows={2}
          placeholder="此场景的对白内容..."
          onChange={(e) => handleFieldChange('audioElements.dialogue', e.target.value)}
          defaultValue={scene.audioElements?.dialogue}
        />
      </Form.Item>

      <Form.Item
        label="音效描述"
        name="audio.soundEffects"
      >
        <TextArea
          rows={2}
          placeholder="所需的音效，如：脚步声、环境音等..."
          onChange={(e) => handleFieldChange('audioElements.soundEffects', e.target.value)}
          defaultValue={scene.audioElements?.soundEffects}
        />
      </Form.Item>
    </Form>
  )

  // 附件管理面板
  const AttachmentsPanel = () => (
    <Space direction="vertical" style={{ width: '100%' }} size="large">
      <Card 
        title={
          <Space>
            <FileImageOutlined />
            <span>参考图片</span>
          </Space>
        }
        size="small"
      >
        <Upload
          listType="picture-card"
          showUploadList={{
            showPreviewIcon: true,
            showRemoveIcon: true,
          }}
          beforeUpload={() => false} // 阻止自动上传
        >
          <div>
            <PlusOutlined />
            <div style={{ marginTop: 8 }}>上传图片</div>
          </div>
        </Upload>
        <Text type="secondary" style={{ fontSize: '12px' }}>
          支持上传参考图片、故事板草图等
        </Text>
      </Card>

      <Card 
        title="故事板手绘稿"
        size="small"
      >
        <Upload
          beforeUpload={() => false}
          showUploadList={{
            showPreviewIcon: true,
            showRemoveIcon: true,
          }}
        >
          <Button icon={<UploadOutlined />}>
            上传手绘稿
          </Button>
        </Upload>
      </Card>
    </Space>
  )

  return (
    <Card
      title={`场景详情 - ${scene.title || `场景 ${scene.order + 1}`}`}
      variant="borderless"
    >
      <Tabs
        activeKey={activeTab}
        onChange={setActiveTab}
        type="card"
        size="small"
      >
        <TabPane tab="基础信息" key="basic">
          <BasicInfoPanel />
        </TabPane>
        <TabPane tab="角色道具" key="elements">
          <ElementsPanel />
        </TabPane>
        <TabPane tab="制作信息" key="production">
          <ProductionPanel />
        </TabPane>
        <TabPane tab="附件管理" key="attachments">
          <AttachmentsPanel />
        </TabPane>
      </Tabs>
    </Card>
  )
}

export default SceneDetailPanel